package com.gang.mars.basic.jdk18.spliterator;

import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

/**
 * @Author：gang.chen
 * @Date：2023/9/4 17:11
 */
public class GangSpliterator {


    static String str = "1|2|3\n" +
            "200|300|400\n" +
            "800|500|600\n" +
            "100|900|200\n" +
            "12|21|77\n" +
            "32|47|90\n" +
            "43|87|31\n" +
            "56|34|57\n" +
            "67|26|73\n";

    public static void main(String[] args) {

        GangTextLine textLine = new GangTextLine(str);
        textLine.stream().forEach(System.out::println);

    }

    static class GangTextLine{

        public final String[] data;


        GangTextLine(String text) {
            this.data = text.split("\n");
        }

        public Stream<String> stream()
        {
            return StreamSupport.stream(new GangTextLineSpliterator(),false);
        }

        class GangTextLineSpliterator implements Spliterator<String>
        {
            private int runTime = 0;

            private int start, end;

            public GangTextLineSpliterator() {
                this.start = 0;
                this.end = GangTextLine.this.data.length - 1;
            }

            public GangTextLineSpliterator(int start, int end) {
                this.start = start;
                this.end = end;
            }

            @Override
            public boolean tryAdvance(Consumer<? super String> action) {

                runTime ++;

                System.out.println("++++++++++"+ runTime + "++++++++++");
                if (start <= end) {
                    action.accept(GangTextLine.this.data[start ++ ]);
                    return true;
                }

                return false;
            }

            @Override
            public Spliterator<String> trySplit() {

                int mid = (end - start) / 2;

                if (mid <= 1) {
                    return null;
                }

                int left = start;
                int right = start + mid;

                start = start + mid + 1;

                return new GangTextLineSpliterator(left, right);
            }

            @Override
            public long estimateSize() {
                return end - start;
            }

            @Override
            public long getExactSizeIfKnown() {
                return estimateSize();
            }

            @Override
            public int characteristics() {
                return IMMUTABLE | SIZED | SUBSIZED;
            }
        }
    }


}
